package com.jn.algorithm.day013.question39;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 江南大学1033190417
 * @date 2022/4/28 10:16
 */
public class Solution {

    //回溯
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> combine = new ArrayList<Integer>();
        dfs(candidates, target, ans, combine, 0);
        return ans;
    }

    public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<Integer>(combine));
            return;
        }
        // 直接跳过
        dfs(candidates, target, ans, combine, idx + 1);
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            combine.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], ans, combine, idx);
            combine.remove(combine.size() - 1);
        }
    }


    //自己写
    public List<List<Integer>> myCombinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        myDfs(res,combine,candidates,0,target);
        return res;
    }

    public void myDfs(List<List<Integer>> res, List<Integer> combine, int[] candidates, int index, int target) {
        if (index == candidates.length) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(combine));
            return;
        }
        myDfs(res, combine, candidates, index + 1, target);//跳过当前这个数
        //选择当前这个数
        if (target - candidates[index] >= 0) {
            combine.add(candidates[index]);
            myDfs(res, combine, candidates, index, target - candidates[index]);
            combine.remove(combine.size() - 1);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{2, 3, 5};
        int target = 8;
        System.out.println(solution.myCombinationSum(nums, target));
    }
}
